var app = require('express')

var headerfix = require('../plugins/headerFix')

var sqlmodule = require('../plugins/sql')//全局共享的实例

var statusobj = require('../plugins/routerStatus')

var formatterDate = require('../plugins/arrDateFormatter')

var pageset = require('../plugins/pageset')

var sqlinits = sqlmodule.sqlinit

var routers = app.Router()

// routers

headerfix(routers)

/**
 * @param {
 *  row:Number,pagesize:Number,iddesc:'1为倒序,反之不是'
 * }
 */

routers.get('/sqllist', (req, res) => {

    //req.query
    //res.send
    var linkend = (type, result) => {
        type == -1 ?
            res.send({
                msg: 'fail',
                status: statusobj.fail,
                data: result
            }) :
            res.send({
                msg: req.query.id || 'ok',
                status: statusobj.ok,
                data: result.type == 'listget' ? result.data : {},
                total: result.type == 'listget' ? result.total : 0,
                pagesize: result.type == 'listget' ? result.pagesize : 1
            })
    }//
    const getListCounts = () => {
        return new Promise((resv, rej) => {
            sqlinits(res, (conn) => {
                conn.query('select count(*) from list', (err, result) => {
                    conn.release();
                    if (err) {
                        rej({ data: err, type: 'countget' })
                    } else {
                        resv(result)
                    }
                })
            })
        })
    }
    const getList = (rest) => {

        var pageobj = pageset.pageget(req, rest)

        var orderarr = [req.query.iddesc == 1 ? ' id DESC' : ' id']

        var sqltemp = '' +
            'select * from list'
            + ' order by' + orderarr.join(',')
            + pageobj.row
            + pageobj.pagesize

        var succ = (result) => {
            return { data: formatterDate(result), type: 'listget', total: pageobj.total, pagesize: pageobj.maxpagesize }
        }
        return new Promise((resv, rej) => {
            sqlinits(res, (conn) => {
                conn.query(sqltemp, (err, result) => {
                    conn.release();
                    if (err) {
                        rej({ data: err, type: 'listget' })
                    } else {
                        resv(succ(result))
                    }
                })
            })
        })
    }//
    getListCounts()
        .then((resv) => {
            return getList(resv)
        })
        .then((resv) => {
            linkend(null, resv)
        })
        .catch((err) => {
            linkend(-1, err)
        })
})

module.exports = routers